package space.edge.d.demo.qrcode.codescanner.scanner;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;

/**
 * Created by gsl on 2017/10/27.
 */

public class PreviewUtil {

    public static int findAppropriateCameraId(@NonNull Context context, boolean back) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return findCameraIdAboveL(context, back);
        } else {
            return findCameraIdBelowL(back);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static int findCameraIdAboveL(Context context, boolean back) {
        CameraManager cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        String[] cameraIds;
        try {
            cameraIds = cameraManager.getCameraIdList();
            for (String id : cameraIds) {
                CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id);
                int facing = characteristics.get(CameraCharacteristics.LENS_FACING);

                if (facing == CameraMetadata.LENS_FACING_BACK && back)
                    return Integer.parseInt(id);
                if (facing == CameraMetadata.LENS_FACING_FRONT && !back)
                    return Integer.parseInt(id);
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        return Integer.MIN_VALUE;
    }

    private static int findCameraIdBelowL(boolean back) {
        int count = Camera.getNumberOfCameras();
        Camera.CameraInfo info = new Camera.CameraInfo();
        for (int i = 0; i < count; i++) {
            Camera.getCameraInfo(i, info);
            if (Camera.CameraInfo.CAMERA_FACING_BACK == info.facing && back)
                return i;
            if (Camera.CameraInfo.CAMERA_FACING_FRONT == info.facing && !back)
                return i;
        }
        return Integer.MIN_VALUE;
    }
}
